<?php

/**
 * @package Framework03
 * @author Walter Tamboer
 */

/**
 * Will create a MySQL connection.
 */
class MySQLConnection extends DatabaseConnection
{
	/**
	 * @var resource The connection handle.
	 */
	protected $Handle;
	/**
	 * Connect to the host
	 */
	public function Connect()
	{
		$this->Handle = @mysql_connect($this->Hostname, $this->Username, $this->Password);

		if (!$this->Handle)
			throw new Exception(mysql_error(), mysql_errno());
	}
	/**
	 * Closes the connection with the host.
	 */
	public function Disconnect()
	{
		@mysql_close($this->Handle);
	}
	/**
	 * Selects a database according to the given name.
	 * @param string $Name The name of the database to select.
	 */
	public function Select($Name)
	{
		$Res = @mysql_select_db($Name, $this->Handle);

		if (!$Res)
			throw new Exception(mysql_error(), mysql_errno());
	}
	/**
	 * Executes a query on the server.
	 * @param string $Sql The SQL query to executes.
	 * @return DatabaseResult Returns a DatabaseResult object or null if the query failed.
	 */
	public function Query($Sql)
	{
		$Query = @mysql_query($Sql);
		
		if (!$Query)
			throw new Exception(mysql_error(), mysql_errno());

		$Result = new MySQLResult($this, $Query);

		return $Result;
	}
	/**
	 * Creates a safe integer from the given input.
	 * @param int $Input The input to escape.
	 * @return int Returns the escaped integer.
	 */
	public function EscapeInteger($Input)
	{
		return intval($Input);
	}
	/**
	 * Creates a safe string from the given input.
	 * @param string $Input The input to escape.
	 * @return string Returns the escaped string.
	 */
	public function EscapeString($Input)
	{
		return @mysql_real_escape_string($Input);
	}
	/**
	 * Gets the connection pointer.
	 * @return resource Returns a resource value that contains the handle of this connection.
	 */
	public function GetHandle()
	{
		return $this->Handle;
	}
}

/**
 * Result of a MySQL query
 */
class MySQLResult extends DatabaseResult
{
	/**
	 * Gets a row from the database.
	 * @return object Returns an object with the result.
	 */
	public function Fetch()
	{
		return @mysql_fetch_object($this->Query);
	}
	/**
	 * Gets the selected rows.
	 * @return int Returns an integer with the amount of selected rows.
	 */
	public function Size()
	{
		return @mysql_num_rows($this->Query);
	}
	/**
	 * Gets the last inserted ID.
	 * @return int Returns an integer with the last inserted ID.
	 */
	public function GetInsertID()
	{
		return mysql_insert_id($this->Connection->GetHandle());
	}
}

?>